/*
 * Copyright (C) 2000-2008 Jens Nixdorf and various contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies of the Software, its documentation and marketing & publicity
 * materials, and acknowledgment shall be given in the documentation, materials
 * and software packages that this Software was used.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package org.mopore.jat.plugin;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mopore.jat.Main;

public class PluginFileAccessJaxB implements IPluginFileAccess {

	private static final String CAN_NOT_PERSIST_OBJECT_WITH_JAX_B = "Can not persist object with JAX-B";
	private final Log log = LogFactory.getLog(getClass().getName());
	private static final String CAN_NOT_RETRIEVE_OBJECT_WITH_JAX_B = "Can not retrieve object with JAX-B";
	private static final String XML_EXTENSION = ".xml";
	private static final String CAN_NOT_GET_APPLICATION_DIRECTORY = "Can not get application directory"; 

	final private File fileAccessDiretory;
	
	public PluginFileAccessJaxB( Class<? extends IJatPluginInternal> pluginInternalClass ) {
		
		Log log = LogFactory.getLog( PluginFileAccessJaxB.class.getName() );
		
		File directory = Main.META_DIR;
		File[] childs = directory.listFiles();
		
		String packageName = pluginInternalClass.getPackage().getName();
		
		File fileAccessDiretory = null;
		
		for ( File child : childs ) {
			String name = child.getName();
			
			if ( packageName.equals( name ) ) {
				fileAccessDiretory = child;
				log.debug( "fileacces directory found: " + fileAccessDiretory );
				break;
			}
		}
		
		if ( fileAccessDiretory == null ) {
			fileAccessDiretory = new File( directory, packageName );
			fileAccessDiretory.mkdir();
			log.info( "new directory created for file access: " + fileAccessDiretory );
		}
		
		log.debug( "retrieving file access directory: " + fileAccessDiretory );
		
		this.fileAccessDiretory = fileAccessDiretory;
	}
	
	
	
	public File getDirectory() {
		return fileAccessDiretory;
	}
	

	public <T> void persist(T jaxbAnnotaedObject) throws IOException  {
		try {
			Class<?>[] boundClasses = new Class[] { jaxbAnnotaedObject
					.getClass() };
			JAXBContext jc = JAXBContext.newInstance(boundClasses);
			String typeName = jaxbAnnotaedObject.getClass().getName();
			typeName = typeName + XML_EXTENSION;
			File file = new File(fileAccessDiretory, typeName);
			Writer writer = new FileWriter(file);
			Marshaller marshaller = jc.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.marshal(jaxbAnnotaedObject, writer);
			writer.close();
		} catch (Exception e) {
			log.error( CAN_NOT_PERSIST_OBJECT_WITH_JAX_B, e );
			throw new IOException( CAN_NOT_PERSIST_OBJECT_WITH_JAX_B, e );
		}		
	}

	
	@SuppressWarnings("unchecked")
	public <T> T retrieve( Class<T> clazz ) throws IOException {
		
		Reader reader = null;
		File file = null;
		try {
			Class<?>[] boundClasses = new Class[] { clazz };
			JAXBContext jc = JAXBContext.newInstance(boundClasses);
			String typeName = clazz.getName();
			typeName = typeName + XML_EXTENSION;
			file = new File(fileAccessDiretory, typeName);
			boolean fileExists = file.exists();
			
			T t = null;
			if ( fileExists ) {
				reader = new FileReader(file);
				Unmarshaller unMarshaller = jc.createUnmarshaller();
				t = (T) unMarshaller.unmarshal(file);
				reader.close();
			}
			else {
				t = clazz.newInstance();
			}
			return t;
		} catch (Exception e) {
			log.error( CAN_NOT_GET_APPLICATION_DIRECTORY, e );
			throw new IOException( CAN_NOT_RETRIEVE_OBJECT_WITH_JAX_B, e );
		}
		finally {
			try {
				if ( reader != null ) {
					reader.close();
				}
			} catch (RuntimeException e) {
				// we don't care
			}
		}
	}

}
